package controllers

import (
	"encoding/json"
	"github.com/Baidu-AIP/golang-sdk/aip/censor"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"shang/conmon"
	"sync"
)

type ImController struct {
	beego.Controller
}
type Message struct {
	UserId   int    `json:"user_id" form:"user_id"`
	FriendId int    `json:"friend_id" form:"friend_id"`
	Content  string `json:"content" form:"content"`
	Cmd      int    `json:"cmd" form:"cmd"`
}

type Node struct {
	Conn *websocket.Conn
	Data chan []byte
}

var wg sync.WaitGroup
var ClientMap = make(map[int]*Node)

func (i *ImController) Im() {
	userid := conmon.Userid
	upgrade := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, err := upgrade.Upgrade(i.Ctx.ResponseWriter, i.Ctx.Request, nil)
	if err != nil {
		log.Println("websocket连接失败", err)
		return
	}
	node := &Node{
		Conn: conn,
		Data: make(chan []byte, 50),
	}
	ClientMap[userid] = node
	wg.Add(2)
	go SendMsg(node)
	go ReadMsg(node)
	wg.Wait()
}
func SendMsg(node *Node) {
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			log.Println("实时获取信息失败", err)
		}
		var msg Message
		json.Unmarshal(message, &msg)
		client := censor.NewClient("DRwZgWBGbowFcCYnljTuvKtU", "hNHLms0neKVKhB8dH8fkD24wMy65x4fA")
		res := client.TextCensor(msg.Content)
		var resMap map[string]interface{}
		json.Unmarshal([]byte(res), &resMap)
		if resMap["conclusion"] == "不合规" {
			log.Println("您的消息不合规")
			node.Conn.WriteMessage(websocket.TextMessage, []byte("您的消息不合规"))
			msg.Content = "*****"
		}
		FriendMap, ok := ClientMap[msg.FriendId]
		if ok {
			FriendMap.Data <- []byte(msg.Content)
		}
	}
}
func ReadMsg(node *Node) {
	wg.Done()
	for {
		select {
		case data := <-node.Data:
			err := node.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				log.Println("管道获取消息失败", err)
			}
		}
	}
}
